import os
import subprocess
import time
import shlex
import logging

# Importing My Modules
import readconfig

# Declaring Globals
serverPids = {}
serverDirectory = readconfig.readConfig(option = "serverDirectory")
program = readconfig.readConfig(option = "program")
serverArg1 = readconfig.readConfig(option = "serverArg1")
serverArg2 = readconfig.readConfig(option = "serverArg2")
serverArg3 = readconfig.readConfig(option = "serverArg3")

# Needs code clean up once functionality is established...


def startAllServers(varNumberServers, varStartServer):
    """Starts all servers, takes 2 params, the number of servers and
        the starting server (first). This function will loop over the startServer
        function."""
    
    while varNumberServers >= varStartServer:
        startServer(str(varStartServer))
        varStartServer = varStartServer + 1
        print "INFO: Waiting Seconds for IO...\n" #DEBUG
        time.sleep(5)
        
    return True


def stopAllServers(varNumberServers, varStartServer):
    """Stops all servers, takes 2 params, the number of servers and
        the starting server (first). This function will loop over the stopServer
        function."""
    
    while varNumberServers >= varStartServer:
        if checkPid(varStartServer) == True:
            stopServer(str(varStartServer))
        else:
            print "Already offline"      
        varStartServer = varStartServer + 1
    return True


def restartAllServers(varNumberServers, varStartServer):
    """Restarts all servers, takes 2 params, the number of servers and
        the starting server (first). This function will loop over the
        restartServer function."""
    
    while varNumberServers >= varStartServer:
        restartServer(str(varStartServer))
        varStartServer = varStartServer + 1  
    return None


def restartOfflineServers(*offlineServerList):
    for num in offlineServerList[0]:
        t = startclasstest.StartServer(args=(num), name="ServerThread-"+(str(num)))
        t.start()
        time.sleep(0.5)
    return True


def storePid(num, pid):
    """A simple function which stores PIDS into a dictionary everytime
        a server is launched."""
    
    global serverPids
    serverPids[str(num)] = pid
    return True


def checkPid(num, returnPid = False):
    global serverPids
    
    num = str(num)
    try:
        check = serverPids[num]
        if returnPid == True:
            return check
    except KeyError:
        return False
    
    try:
        os.kill(int(check), 0)
        return True
    except OSError:
        return False


def checkAllServers(varNumberServers, varStartServer, returnOfflineOnly = True): #Should I use a dict?
    offlineServerList = []
    onlineServerList = []
    dictServerStatus = {}
    
    while varNumberServers >= varStartServer:
        if checkPid(varStartServer) != True:            #Server is offline
            offlineServerList.append(varStartServer)
            dictServerStatus[varStartServer] = False
        else:                                           #Server is online
            onlineServerList.append(varStartServer)
            dictServerStatus[varStartServer] = True
        
        varStartServer = varStartServer + 1
        
    if returnOfflineOnly == True:
        return offlineServerList
    elif returnOfflineOnly == False:
        return onlineServerList
    elif returnOfflineOnly == "all":
        return dictServerStatus
    else:
        return dictServerStatus


def displayServerStatus(dictServers = {}, option = "all"):
    serverList = {}


    for k in dictServers:
        v = dictServers[k]
        if v == True:
            t = "online"
        elif v == False:
            t = "offline"

        if option == "offline" and v == False:
            serverList[k] = "Server #" + str(k), "is", str(t), "with PID of:", checkPid(k, returnPid = True)
            print "Server #" + str(k), "is", str(t), "with PID of:", checkPid(k, returnPid = True)
        elif option == "online" and v == True:
            serverList[k] = "Server #" + str(k), "is", str(t), "with PID of:", checkPid(k, returnPid = True)
            print "Server #" + str(k), "is", str(t), "with PID of:", checkPid(k, returnPid = True)
        elif option == "all" and (v == True or v == False):
            serverList[k] = "Server #" + str(k), "is", str(t), "with PID of:", checkPid(k, returnPid = True)
            print "Server #" + str(k), "is", str(t), "with PID of:", checkPid(k, returnPid = True)
            
    return serverList


